﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace NExplorer
{
	internal class AddInManager
	{
		private static readonly List<IAddIn> s_loadedAddIns = new List<IAddIn>();

		public static void LoadAddIns()
		{
		    string addInsPath = Path.Combine(Application.StartupPath, "AddIns");

		    if (Directory.Exists(addInsPath))
		    {
                string addInTypeName = typeof(IAddIn).FullName;
                
                foreach (string filename in Directory.GetFiles(addInsPath, "*.dll"))
		        {
		        	try
		        	{
		        		Assembly assm = Assembly.LoadFrom(filename);

		        		foreach (Type type in assm.GetTypes())
						{
							if (type.GetInterface(addInTypeName) != null)
							{
	                			try
	                			{
	                				IAddIn addIn = (IAddIn)Activator.CreateInstance(type);
	                				addIn.Initialize();
									s_loadedAddIns.Add(addIn);
	                			}
	                			catch (Exception e)
	                			{
	                				string text = string.Format("Error creating add-in type '{0}':\n\n{1}", type.Name, e.Message);
		        					MessageBox.Show(text, "Error Creating AddIn", MessageBoxButtons.OK, MessageBoxIcon.Error);
	                			}
							}
						}
		        	}
		        	catch (Exception e)
		        	{
		        		string text = string.Format("Error while loading add-in assembly '{0}':\n\n{1}", filename, e.Message);
		        		MessageBox.Show(text, "Error Loading AddIn", MessageBoxButtons.OK, MessageBoxIcon.Error);
		        	}
		        }
		    }
		}

		public static List<IAddIn> LoadedAddIns
		{
			get { return s_loadedAddIns; }
		}
	}
}
